#!/usr/bin/python2
#-*- coding:utf-8 -*-

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from sklearn import svm
import numpy as np
import sys, time
from uifile import mainui, histhand
from PIL import Image
from imgRec1 import Div
from tempData import tmpData as td
from pic2text import PicToText as p2t
import os

QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8"))

class UITest(QDialog):
    """docstring for UITest"""
    def __init__(self, parent = None):
        super(UITest, self).__init__(parent)
        self.mui = mainui.Ui_Dialog()
        self.mui.setupUi(self)

        self.im = None

        self.connect(self.mui.pushButton_2, SIGNAL("clicked()"), self.slotsel) # select picture
        self.connect(self.mui.pushButton, SIGNAL("clicked()"), self.slotdiv) # division picture
        self.connect(self.mui.pushButton_3, SIGNAL("clicked()"), self.slothist) # user input hist
        self.connect(self.mui.pushButton_4, SIGNAL("clicked()"), self.updatepic) # update threshold
        self.connect(self.mui.pushButton_5, SIGNAL("clicked()"), self.p2tTest) # test func

    '''
    slot function
    user select cpatcha
    '''
    def slotsel(self):
        #init label
        self.mui.label_4.setText('pict1')
        self.mui.label_5.setText('pict2')
        self.mui.label_6.setText('pict3')
        self.mui.label_7.setText('pict4')
        # print "select folder"
        # directory1 = QFileDialog.getExistingDirectory(self,  
        #                             "select folder",  
        #                             "../")                                 
        # print(directory1) 

        # select picture file
        filename = QFileDialog.getOpenFileName(self, 
                                    "select file", 
                                    "./picture_source", 
                                    "All Files (*);;picture Files (*.png)")
        
        #select file success
        if filename:
            self.printInfo('file absolute path: ' + filename, False)
            #import image test
            img = str(filename)
            print img
            self.im = Image.open(img)
            # print im
            msg = ''
            image = QImage()
            if image.load(str(filename)):
                print "load file ok"
                #self.printInfo('load file done.')
                msg = msg + 'load file done.' + '\n'
                limg = image.scaled(180, 60)
                self.mui.label.setPixmap(QPixmap.fromImage(limg))
            d = Div(self.im)
            td.img = self.im
            tres = d.denoiseAuto()
            #msg = 'get hist threshold value: ' + str(tres)
            msg = msg + 'get auto hist threshold value: ' + str(tres) + '\n'
            self.printInfo(msg, True)
            im2 = Image.open('./picture_cache/testgray.png') #gary picture
            im3 = Image.open('./picture_cache/test.png') # binary picture
            #print im2, im3
            image2 = QImage()
            if image2.load('./picture_cache/testgray.png'):
                print "gray picture load done"
                self.printInfo('gray picture load done', True)
                limg = image2.scaled(180, 60)
                self.mui.label_2.setPixmap(QPixmap.fromImage(limg))
            else:
                print "load failed"
                self.printInfo('file load failed', True)
            image3 = QImage()
            if image3.load('./picture_cache/test.png'):
                print "binary picture load done"
                self.printInfo('binary picture load done', True)
                limg = image3.scaled(180, 60)
                self.mui.label_3.setPixmap(QPixmap.fromImage(limg))
            else:
                print "load failed"
                self.printInfo('file load failed', True)
        else:
            print "select file failed"
            self.printInfo('select file failed.')
        # input hist number should after select action
        self.mui.pushButton_3.setEnabled(True)

    '''
    slot function
    start division cpatcha
    '''
    def slotdiv(self):
        if self.im == None:
            print "No picture load"
            self.printInfo('no picture load, choose a picture')
        else:
            import os
            os.system('rm ./picture_cache/D*.png')
            os.system('rm ./txt_cache/D*.txt')
            d = Div(self.im)
            imgpieces = d.mainDivision()
            pieces = td.list1
            len_p = len(pieces)
            print len_p
            msg0 = ''
            for i in range(len_p):
                msg0 = msg0 + str(pieces[i]) + '\n'
            self.printInfo(msg0)
            image4 = QImage()
            if image4.load('./picture_cache/DIVISIONED_1.png'):
                self.mui.label_4.setPixmap(QPixmap.fromImage(image4))
            image5 = QImage()
            if image5.load('./picture_cache/DIVISIONED_2.png'):
                self.mui.label_5.setPixmap(QPixmap.fromImage(image5))
            image6 = QImage()
            if image6.load('./picture_cache/DIVISIONED_3.png'):
                self.mui.label_6.setPixmap(QPixmap.fromImage(image6))
            image7 = QImage()
            if image7.load('./picture_cache/DIVISIONED_4.png'):
                self.mui.label_7.setPixmap(QPixmap.fromImage(image7))
        self.mui.pushButton_4.setEnabled(False)
        self.mui.pushButton_5.setEnabled(True)
        self.mui.label_11.setText('output here')

    def updatepic(self):
        d = Div(self.im)
        d.denoiseHand()
        image3 = QImage()
        if image3.load('./picture_cache/test.png'):
            print "binary picture reload done"
            self.printInfo('binary picture load done', True)
            limg = image3.scaled(180, 60)
            self.mui.label_3.setPixmap(QPixmap.fromImage(limg))
            self.mui.pushButton_4.setEnabled(False)
            self.printInfo(td.msg, True)

    '''
    slot function
    user input hist threshold
    '''
    def slothist(self):
        print "hist threshold"
        self.printInfo('open input hist threshold dialog')
        h = histH()
        h.show()
        h.exec_()
        self.mui.pushButton_4.setEnabled(True)

    '''
    slot function
    output verification code as string or list
    '''
    def p2tTest(self):
        self.printInfo('pic to txt test for mlearn')
        images = os.listdir('./picture_cache/')
        for pic in images:
            #print p
            arg = './picture_cache/'+pic
            p = p2t(arg)
            p.image2text(arg)
        
        #verification machine learn with svm
        path = './txt_cache/'
        txt = os.listdir(path)
        dict = {}
        i = 0 #compare index

        classifier = svm.NuSVC(gamma=0.0001)
        x, y = self.loadData()
        classifier.fit(x, y)

        for t in txt:
            arg = path + t
            fp = open(arg)
            testdata = []
            imgdata = []
            for i in range(32):
                lineStr = fp.readline()
                for j in range(32):
                    imgdata.append(lineStr[j])
            testdata.append(imgdata)
            fp.close
            #use classifier data
            predicted = classifier.predict(testdata)
            #list to string
            s1 = ''.join(predicted)
            #print t + '=' + s1
            #use . replace _ and split it get number
            w = str(t).replace('_', '.').split('.')[1]
            #print w
            index = int(w)
            dict[index] = s1
        #s = ''
        out = dict.values()
        s = ''.join(out)
        print out
        print s
        self.mui.label_11.setText(s)
        self.mui.pushButton_5.setEnabled(False)

    '''
    loaddata function
    study samples for machine learn
    paramter: path of study datas
    return data vector and label
    '''
    def loadData(self, path='../samples/imagedata/'):
        files = os.listdir(path) 
        data = []
        label = []
        for f in files:
            fp = open(path+f)
            name = f.split('_')[0]
            imgdata = []
            label.append(name)
            for i in range(32):
                lineStr = fp.readline()
                for j in range(32):
                    imgdata.append(lineStr[j])
            data.append(imgdata)
            fp.close()
        returnVect = np.array(data)
        return returnVect, label

    '''
    a print function
    print message to textedit
    '''
    def printInfo(self, msg, showtime = True):
        self.mui.textEdit.append('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -')
        if msg == '':
            msg = 'divided failed'
        if True == showtime:
            #pass
            timemsg = time.strftime("%H:%M:%S",time.localtime(time.time()))
            timemsg = '[' + timemsg + ']  '
            self.mui.textEdit.append(timemsg)
            self.mui.textEdit.append(msg)
            #backspace...delete previous char -> \n
            self.mui.textEdit.moveCursor(QTextCursor.StartOfLine)
            self.mui.textEdit.textCursor().deletePreviousChar()
            self.mui.textEdit.moveCursor(QTextCursor.EndOfLine)
        else:
            self.mui.textEdit.append(msg)

'''
a dialog class
show input hist threshold
'''
class histH(QDialog):
    def __init__(self, parent = None):
        super(histH, self).__init__(parent)
        self.histh = histhand.Ui_Dialog()
        self.histh.setupUi(self)
        #init value
        self.im = td.img
        self.thresholdL = 0
        self.thresholdH = 255

        self.connect(self.histh.pushButton, SIGNAL("clicked()"), self.acc)
        
    def acc(self):
        #td.thresholdL = self.histh.lineEdit.text()
        self.thresholdL = int(self.histh.lineEdit.text())
        self.thresholdH = int(self.histh.lineEdit_2.text())
        if self.thresholdH > 255 or self.thresholdL < 0:
            QMessageBox.information(self, 'waming', "out of threshold range")
        elif self.thresholdH < self.thresholdL:
            QMessageBox.information(self, 'waming', "wrong threshold range")
        else:
            td.thresholdL = self.thresholdL
            td.thresholdH = self.thresholdH
            print td.thresholdL, td.thresholdH
            td.msg = 'threshold rang : ' + str(td.thresholdL) + ' ~ ' + str(td.thresholdH)
            td.denoise = 1
            self.accept()
            h = histH()
            h.close()

app = QApplication(sys.argv)
w = UITest()
w.show()

print "promgram starrrrrrrrrt"
w.printInfo('promgram start')
app.exec_()
